﻿Imports System.Data.SqlClient
Imports System.Security.Cryptography

Module Module1
    Public dbCat As New geriatria.DataClasses1DataContext
    'Public ConectionString As String = "Data Source=localhost\SQLEXPRESS;Initial Catalog=catGediatria;Integrated Security=true"
    Public ConectionString As String = "Data Source=woad.arvixe.com;Initial Catalog=catGediatria;Integrated Security=false;uid=miguel;pwd=miguel;database=catGediatria;"
    'Public ConectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("catGediatriaConnectionString").ConnectionString


    Public Function Nz_String(ByVal result As String) As String
        If Trim(result) = "" Or result = "&nbsp;" Then
            Nz_String = "NULL"
        Else
            Nz_String = "'" & Trim(result.Replace("'", "")) & "'"
        End If
    End Function

    Public Function Nz_Number(ByVal result As String) As String
        If Trim(result) = "" Or result = "&nbsp;" Then
            Nz_Number = "NULL"
        Else
            Nz_Number = Trim(result.Replace("'", ""))
        End If
    End Function

    Public Function seleccione(Optional ByRef SinValue As Boolean = False) As ListItem
        Dim Li As New ListItem
        Li.Text = "Seleccione por favor..."
        If SinValue <> True Then
            Li.Value = ""
        End If
        Li.Attributes.CssStyle.Add("color", "red")
        Return Li
    End Function

End Module

Public Class Sql_Server
    Public Combo As New DropDownList
    Public List_Box As New ListBox
    Public Radio_List As New RadioButtonList
    Public Check_List As New CheckBoxList
    Private Conec As New SqlConnection

    Public MsgError As String

    Public Sub Conectar()
        Try
            Conec.ConnectionString = ConectionString
            Conec.Open()
        Catch ex As Exception
            Debug.Write(ex.Message)
        End Try
    End Sub

    Public Sub Desconectar()
        Conec.Close()
    End Sub

    Public Sub Listar_Combo(ByVal Sqll As String, Optional ByRef sDefault As Boolean = False)
        Combo.DataSource = CreateDataSource(Sqll, sDefault)
        Combo.DataTextField = "Text"
        Combo.DataValueField = "Value"
        Combo.DataBind()
        Combo.SelectedIndex = -1
    End Sub

    Public Sub Listar_List_Box(ByVal Sqll As String)
        List_Box.DataSource = CreateDataSource(Sqll, True)
        List_Box.DataTextField = "Text"
        List_Box.DataValueField = "Value"
        List_Box.DataBind()
        List_Box.SelectedIndex = -1
    End Sub

    Public Sub Listar_Checked_Box(ByVal Sqll As String, Optional ByRef Chk As Boolean = False)
        Check_List.DataSource = CreateDataSource(Sqll, True)
        Check_List.DataTextField = "Text"
        Check_List.DataValueField = "Value"
        Check_List.DataBind()
        If Chk = True Then
            Dim Docmd As New DoCmd, reader As SqlClient.SqlDataReader
            Docmd.Conectar()
            reader = Docmd.Read_SQL(Sqll)
            While reader.Read()
                Check_List.Items.FindByValue(reader(0).ToString).Selected = reader(2).ToString
            End While
            Docmd.Desconectar()
        End If
        'Check_List.SelectedIndex = -1
    End Sub

    Public Sub Listar_Radio_list(ByVal Sqll As String)
        Radio_List.DataSource = CreateDataSource(Sqll, True)
        Radio_List.DataTextField = "Text"
        Radio_List.DataValueField = "Value"
        Radio_List.DataBind()
        'List_Box.SelectedIndex = -1
    End Sub

    Public Sub Listar_Radio_list_Logicos()
        Radio_List.DataSource = CreateDataSource_Logicos()
        Radio_List.DataTextField = "Text"
        Radio_List.DataValueField = "Value"
        Radio_List.DataBind()
    End Sub

    Function CreateDataSource_Logicos() As ICollection
        Dim dt As DataTable = New DataTable()
        dt.Columns.Add(New DataColumn("Value", GetType(String)))
        dt.Columns.Add(New DataColumn("Text", GetType(String)))
        dt.Rows.Add(CreateRow(1, "Si", dt))
        dt.Rows.Add(CreateRow(0, "No", dt))
        Dim dv As DataView = New DataView(dt)
        Return dv
    End Function

    Public Sub Listar_Radio_list_numeros(ByVal ini As Integer, ByVal fin As Integer)
        Radio_List.DataSource = CreateDataSource_Numeros(ini, fin)
        Radio_List.DataTextField = "Text"
        Radio_List.DataValueField = "Value"
        Radio_List.DataBind()
    End Sub

    Function CreateDataSource_Numeros(ByVal ini As Integer, ByVal fin As Integer) As ICollection
        Dim dt As DataTable = New DataTable()
        dt.Columns.Add(New DataColumn("Value", GetType(String)))
        dt.Columns.Add(New DataColumn("Text", GetType(String)))
        For i = ini To fin
            dt.Rows.Add(CreateRow(i, i & ".", dt))
        Next
        Dim dv As DataView = New DataView(dt)
        Return dv
    End Function

    Function CreateDataSource(ByVal Sql As String, Optional ByVal List As Boolean = False) As ICollection
        Dim dt As DataTable = New DataTable()
        Dim cm As New SqlCommand, dr As SqlDataReader
        cm.CommandType = CommandType.Text
        cm.CommandText = Sql
        cm.Connection = Conec
        dr = cm.ExecuteReader()
        dt.Columns.Add(New DataColumn("Value", GetType(String)))
        dt.Columns.Add(New DataColumn("Text", GetType(String)))
        If List <> True Then
            dt.Rows.Add(CreateRow(-1, "Elija", dt))
        End If
        While dr.Read
            dt.Rows.Add(CreateRow(dr(0).ToString, dr(1).ToString, dt))
        End While
        dr.Close()
        Dim dv As DataView = New DataView(dt)
        Return dv
    End Function

    Function CreateRow(ByVal Text As String, ByVal Value As String, ByVal dt As DataTable) As DataRow
        Dim dr As DataRow = dt.NewRow()
        dr(0) = Text
        dr(1) = Value
        Return dr
    End Function

    Public Function DLookup(ByVal campo As String, ByVal tabla As String, Optional ByVal criterio As String = " WHERE 1") As String
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            If criterio <> " WHERE 1" Then criterio = " WHERE " & criterio
            cmd.CommandText = "SELECT " & campo & " FROM " & tabla & criterio
            reader = cmd.ExecuteReader
            DLookup = ""
            While reader.Read
                DLookup = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            Return ""
        End Try
    End Function

End Class

Public Class DoCmd
    Private Conec As New SqlConnection
    Public MsgError As String
    Public MsgrLinea As String

    Public Sub Conectar()
        Conec.ConnectionString = ConectionString
        Conec.Open()
    End Sub

    Public Sub Desconectar()
        Conec.Close()
    End Sub

    Public Function RunSQL(ByVal Sqll As String, Optional ByRef Batch As Boolean = False) As Boolean
        Dim Transaction As SqlTransaction
        Transaction = Conec.BeginTransaction("rub")
        Try
            Dim cm As New SqlCommand, Result As Integer
            cm.CommandType = CommandType.Text
            cm.CommandText = Sqll
            cm.Connection = Conec
            cm.Transaction = Transaction
            Result = cm.ExecuteNonQuery
            Transaction.Commit()
            If Result > 0 Then
                Return True
            ElseIf Result = -1 And Batch = True Then
                Return True
            Else
                Return False
            End If
        Catch ex As SqlException
            Transaction.Rollback()
            MsgError = ex.Message
            If Batch = True Then
                MsgrLinea = ""
                For i = 0 To ex.Errors.Count - 1
                    If MsgrLinea.Contains(ex.Errors(i).LineNumber) = False Then
                        MsgrLinea = MsgrLinea & ex.Errors(i).LineNumber & ","
                    End If
                Next i
                MsgrLinea = Mid(MsgrLinea, 1, Len(MsgrLinea) - 1) & ""
            End If
            Return False
        End Try
    End Function

    Public Function Read_SQL(ByVal Sqll As String) As SqlDataReader
        Try
            Dim cm As New SqlCommand
            cm.CommandType = CommandType.Text
            cm.CommandText = Sqll
            cm.Connection = Conec
            Read_SQL = cm.ExecuteReader
        Catch ex As Exception
            MsgError = ex.Message
            Read_SQL = Nothing
        End Try
    End Function

    Public Function DLookup(ByVal campo As String, ByVal tabla As String, Optional ByVal criterio As String = " WHERE 1") As String
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            If criterio <> " WHERE 1" Then criterio = " WHERE " & criterio
            cmd.CommandText = "SELECT " & campo & " FROM " & tabla & criterio
            reader = cmd.ExecuteReader
            DLookup = ""
            While reader.Read
                DLookup = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            Return ""
        End Try
    End Function

    Public Function DCount(ByVal campo As String, ByVal tabla As String, Optional ByVal criterio As String = " WHERE 1") As Single
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            If criterio <> " WHERE 1" Then criterio = " WHERE " & criterio
            cmd.CommandText = "SELECT COUNT(" & campo & ") FROM " & tabla & criterio
            reader = cmd.ExecuteReader
            DCount = 0
            While reader.Read
                DCount = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DCount = 0
        End Try
    End Function

    Public Function DMax(ByVal campo As String, ByVal tabla As String, Optional ByVal criterio As String = " WHERE 1") As String
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            If criterio <> " WHERE 1" Then criterio = " WHERE " & criterio
            cmd.CommandText = "SELECT MAX(" & campo & ") FROM " & tabla & criterio
            reader = cmd.ExecuteReader
            DMax = ""
            While reader.Read
                DMax = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DMax = ""
        End Try
    End Function

    Public Function DMin(ByVal campo As String, ByVal tabla As String, Optional ByVal criterio As String = " WHERE 1") As String
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            If criterio <> " WHERE 1" Then criterio = " WHERE " & criterio
            cmd.CommandText = "SELECT MIN(" & campo & ") FROM " & tabla & criterio
            reader = cmd.ExecuteReader
            DMin = ""
            While reader.Read
                DMin = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DMin = ""
        End Try
    End Function

    Public Function DSum(ByVal campo As String, ByVal tabla As String, Optional ByVal criterio As String = " WHERE 1") As Single
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            If criterio <> " WHERE 1" Then criterio = " WHERE " & criterio
            cmd.CommandText = "SELECT SUM(" & campo & ") FROM " & tabla & criterio
            reader = cmd.ExecuteReader
            DSum = 0
            While reader.Read
                DSum = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DSum = 0
        End Try
    End Function

    Public Function RunSQL_ID(ByVal Sqll As String) As String
        'Dim Transaction As SqlTransaction
        'Transaction = Conec.BeginTransaction(IsolationLevel.Serializable, "productiva")
        Try
            Dim cm As New SqlCommand, Result As String, reader As SqlDataReader
            cm.CommandType = CommandType.Text
            cm.CommandText = "SET NOCOUNT ON " & Sqll & " SELECT @@IDENTITY SET NOCOUNT OFF"
            cm.Connection = Conec
            'cm.Transaction = Transaction
            reader = cm.ExecuteReader()
            'Transaction.Commit()
            Result = ""
            While reader.Read
                Result = reader(0).ToString()
            End While
            reader.Close()
            Return Result
        Catch ex As Exception
            'Transaction.Rollback()
            Return ""
            MsgError = ex.Message
        End Try
    End Function

    Public Function Carga_Funcionarios(ByRef sRuta As String) As DataSet
        Try
            Dim cmd As New SqlClient.SqlCommand, dta As New SqlClient.SqlDataAdapter, dt As New DataSet
            Dim strconn As String
            strconn = "Provider=Microsoft.Jet.Oledb.4.0; data source= " & sRuta & ";Extended properties=""Excel 8.0;hdr=yes;imex=1"""
            Dim mconn As New System.Data.OleDb.OleDbConnection(strconn)
            Dim ad As New System.Data.OleDb.OleDbDataAdapter("Select * from [funcionarios$]", mconn)
            mconn.Open()
            ad.Fill(dt)
            mconn.Close()
            Return dt
        Catch ex As Exception
            Return Nothing
            MsgError = ex.Message
        End Try
    End Function

    Public Function Carga_Actividades(ByRef sRuta As String) As DataSet
        Try
            Dim cmd As New SqlClient.SqlCommand, dta As New SqlClient.SqlDataAdapter, dt As New DataSet
            Dim strconn As String
            strconn = "Provider=Microsoft.Jet.Oledb.4.0; data source= " & sRuta & ";Extended properties=""Excel 8.0;hdr=yes;imex=1"""
            Dim mconn As New System.Data.OleDb.OleDbConnection(strconn)
            Dim ad As New System.Data.OleDb.OleDbDataAdapter("Select * from [actividades$]", mconn)
            mconn.Open()
            ad.Fill(dt)
            mconn.Close()
            Return dt
        Catch ex As Exception
            Return Nothing
            MsgError = ex.Message
        End Try
    End Function

    Function GetRandomColor() As String
        Dim rand As New Random, sColor As System.Drawing.Color
        sColor = System.Drawing.Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256))
        Return Right(Hex("00" & sColor.R), 3) & Right(Hex("00" & sColor.G), 3) & Right(Hex("00" & sColor.B), 3)
    End Function

    'SUMAS PERSONALIZADAS
    Public Function DSum_Proyecto(ByVal campo As String, ByVal criterio As String) As Single
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            cmd.CommandText = "SELECT SUM(" & campo & ") FROM pro_proyectos p INNER JOIN pro_subproyectos subp ON p.Id=subp.pro_proyecto_id INNER JOIN act_actividades act ON act.pro_subproyecto_id= subp.Id INNER JOIN age_agenda age ON act.Id=age.act_actividad_id WHERE p.Id=" & criterio & " GROUP BY p.Id"
            reader = cmd.ExecuteReader
            DSum_Proyecto = 0
            While reader.Read
                DSum_Proyecto = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DSum_Proyecto = 0
        End Try
    End Function

    Public Function DSum_Subproyecto(ByVal campo As String, ByVal criterio As String) As Single
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            cmd.CommandText = "SELECT SUM(" & campo & ") FROM pro_subproyectos subp INNER JOIN act_actividades act ON act.pro_subproyecto_id= subp.Id INNER JOIN age_agenda age ON act.Id=age.act_actividad_id WHERE subp.Id=" & criterio & " GROUP BY subp.Id"
            reader = cmd.ExecuteReader
            DSum_Subproyecto = 0
            While reader.Read
                DSum_Subproyecto = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DSum_Subproyecto = 0
        End Try
    End Function

    Public Function DSum_Actividad(ByVal campo As String, ByVal criterio As String) As Single
        Try
            Dim cmd As New SqlCommand, reader As SqlDataReader
            cmd.CommandType = CommandType.Text
            cmd.Connection = Conec
            cmd.CommandText = "SELECT SUM(" & campo & ") FROM act_actividades act INNER JOIN age_agenda age ON act.Id=age.act_actividad_id WHERE act.Id=" & criterio & " GROUP BY act.Id"
            reader = cmd.ExecuteReader
            DSum_Actividad = 0
            While reader.Read
                DSum_Actividad = reader(0).ToString()
            End While
            reader.Close()
        Catch ex As Exception
            MsgError = ex.Message
            DSum_Actividad = 0
        End Try
    End Function
End Class

Public Class Admin_TreeView
    Public Arbol As TreeView

    Public Function Crea_Nodo_Index(ByVal Name As String) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.Expanded = False
        Node.ImageUrl = "images/home_16.png"
        Node.NavigateUrl = "Index.aspx"
        Node.ToolTip = "Panel de Inicio"
        Arbol.Nodes.Add(Node)
        Return Arbol.Nodes.Count - 1
    End Function

    Public Function Crea_Nodo_Padre(ByVal Name As String, ByVal Valor As Integer, ByRef indice As Integer, Optional ByRef selection As Boolean = False) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.Value = Valor
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.Expanded = False
        Node.ImageUrl = "images/briefcase_16.png"
        Node.NavigateUrl = "clientes.aspx?id=" & Valor
        Node.ToolTip = "Clientes"
        If selection = True Then
            Arbol.Nodes(indice).Expand()
            Node.Selected = True
        End If
        Arbol.Nodes(indice).ChildNodes.Add(Node)
        Return Arbol.Nodes(indice).ChildNodes.Count - 1
    End Function

    Public Function Crea_Nodo_Hijos(ByVal Name As String, ByVal Indice As Int16, ByVal Valor As Integer, Optional ByRef selection As Boolean = False) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.Value = Valor
        Node.Expanded = False
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.ImageUrl = "images/1310158946_companies.png"
        Node.NavigateUrl = "sucursales.aspx?id=" & Valor
        Node.ToolTip = Name
        Arbol.Nodes(Indice).ChildNodes.Add(Node)
        If selection = True Then
            Arbol.Nodes(Indice).Expand()
            Node.Selected = True
        End If
        Return Arbol.Nodes(Indice).ChildNodes.Count - 1
    End Function

    Public Function Crea_Nodo_Hijos_Nivel_2(ByVal Name As String, ByVal Indice As Int16, ByVal Indice2 As Int16, ByVal Valor As Integer, ByVal Valor2 As Integer, Optional ByRef selection As Boolean = False, Optional ByRef proyecto As Boolean = False) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.Value = Valor2
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.Expanded = False
        If proyecto = True Then
            Node.NavigateUrl = "proyectos.aspx?clid=" & Valor & "&id=" & Valor2
            Node.ImageUrl = "images/diagram_16.png"
        Else
            Node.NavigateUrl = "administra_sucursales.aspx?clid=" & Valor & "&id=" & Valor2
            Node.ImageUrl = "images/1310158946_companies.png"
        End If
        Node.ToolTip = Name
        Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes.Add(Node)
        If selection = True Then
            Arbol.Nodes(Indice).ChildNodes(Indice2).Expand()
            Node.Selected = True
        End If
        Return Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes.Count - 1
    End Function

    Public Function Crea_Nodo_Hijos_Nivel_3(ByVal Name As String, ByVal Indice As Int16, ByVal Indice2 As Int16, ByVal Indice3 As Int16, ByVal Valor As Integer, ByVal Valor2 As Integer, ByVal Valor3 As Integer, Optional ByRef selection As Boolean = False) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.Value = Valor2
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.Expanded = False
        Node.ImageUrl = "images/1310159740_projection_screen_present.png"
        Node.NavigateUrl = "subproyectos.aspx?clid=" & Valor & "&pro=" & Valor2 & "&id=" & Valor3
        Node.ToolTip = Name
        Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes.Add(Node)
        If selection = True Then
            Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).Expand()
            Node.Selected = True
        End If
        Return Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes.Count - 1
    End Function

    'evaluacion 
    Public Function Crea_Nodo_Hijos_Nivel_4(ByVal Name As String, ByVal Indice As Int16, ByVal Indice2 As Int16, ByVal Indice3 As Int16, ByVal Indice4 As Int16, ByVal Valor As Integer, ByVal Valor2 As Integer, ByVal Valor3 As Integer, ByVal Valor4 As Integer, Optional ByRef selection As Boolean = False) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.Value = Valor3
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.Expanded = False
        Node.ImageUrl = "images/1312565294_checkered_flag.png"
        Node.NavigateUrl = "mejora.aspx?clid=" & Valor & "&pro=" & Valor2 & "&subpro=" & Valor3 & "&id=" & Valor4
        Node.ToolTip = Name
        Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes(Indice4).ChildNodes.Add(Node)
        If selection = True Then
            Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes(Indice4).Expand()
            Node.Selected = True
        End If
        Return Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes(Indice4).ChildNodes.Count - 1
    End Function

    'agenda
    Public Function Crea_Nodo_Hijos_Nivel_4_Agenda(ByVal Name As String, ByVal Indice As Int16, ByVal Indice2 As Int16, ByVal Indice3 As Int16, ByVal Indice4 As Int16, ByVal Valor As Integer, ByVal Valor2 As Integer, ByVal Valor3 As Integer, ByVal Valor4 As Integer, Optional ByRef selection As Boolean = False) As Integer
        Dim Node As New TreeNode
        Node.Text = Name
        Node.Value = Valor3
        Node.SelectAction = TreeNodeSelectAction.Select
        Node.Expanded = False
        Node.ImageUrl = "images/1313602532_schedule.png"
        Node.NavigateUrl = "agenda.aspx?clid=" & Valor & "&pro=" & Valor2 & "&subpro=" & Valor3 & "&id=" & Valor4
        Node.ToolTip = Name
        Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes(Indice4).ChildNodes.Add(Node)
        If selection = True Then
            Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes(Indice4).Expand()
            Node.Selected = True
        End If
        Return Arbol.Nodes(Indice).ChildNodes(Indice2).ChildNodes(Indice3).ChildNodes(Indice4).ChildNodes.Count - 1
    End Function

End Class

Public Class ToPdf
    Public Function HtmlToPdf(ByRef pdf As String, ByRef Html As String, ByRef sRta As String) As Boolean
        Dim result As Boolean = False, message As String
        Dim argument As StringBuilder = New StringBuilder
        argument.Append(" --javascript-delay 1000 ")
        argument.Append(Html & " ")
        argument.Append(pdf)
        Try
            Dim p As System.Diagnostics.Process = New System.Diagnostics.Process
            p.StartInfo.UseShellExecute = False
            p.StartInfo.CreateNoWindow = True
            p.StartInfo.FileName = sRta 'Server.MapPath("bin/wkhtmltopdf.exe")
            p.StartInfo.Arguments = argument.ToString()
            p.StartInfo.RedirectStandardOutput = True
            p.StartInfo.RedirectStandardError = True
            p.Start()
            p.WaitForExit()
            message = p.StandardError.ReadToEnd()
            If message.Contains("Done") Then
                message = p.StandardOutput.ReadToEnd()
                result = True
            Else
                result = False
            End If
            Return result
        Catch ex As Exception
            Return result
        End Try
    End Function
End Class

Public Class AmCharts
    'FLASH
    Public Function genera_chart_Pie_Flash(ByRef DivId As String, ByRef Sdatos As String, ByRef sTitulo As String, ByRef pagina As Page, Optional ByVal ancho As Int32 = 600, Optional ByVal alto As Int32 = 400, Optional ByRef sColors As String = "FF0F00,FF6600,FF9E01,FCD202,F8FF01,B0DE09,04D215,0D8ECF,0D52D1,2A0CD0,8A0CCF,CD0D74,754DEB,DDDDDD,999999,333333,990000") As String
        Try
            Dim cstype As Type = pagina.GetType()
            Dim cs As ClientScriptManager = pagina.ClientScript
            Dim sb As StringBuilder = New StringBuilder()
            sb.AppendLine("var params ={bgcolor: ""#FFFFFF""}")
            sb.AppendLine("var flashVars = { path: ""amcharts/flash/"", chart_settings: encodeURIComponent(""<settings><background><alpha>100</alpha></background><balloon><alpha>77</alpha><border_width>3</border_width><border_color>000000</border_color><corner_radius>5</corner_radius></balloon><legend><enabled>0</enabled><align>center</align></legend><pie><colors>" & sColors & "</colors><y>50%</y><radius>30%</radius><inner_radius>40</inner_radius><height>40</height><angle>20</angle><start_angle>27</start_angle><outline_alpha>13</outline_alpha><brightness_step>24</brightness_step><gradient>radial</gradient></pie><animation><start_time>1.8</start_time><start_radius>251%</start_radius><start_alpha>8</start_alpha><pull_out_time>0.3</pull_out_time></animation><data_labels><show>{title}: {value} %</show><radius>40%</radius><text_size>14</text_size><max_width>160</max_width><line_alpha>7</line_alpha></data_labels><export_as_image><file>amcharts/flash/export.aspx</file><color>#CC0000</color><alpha>50</alpha></export_as_image><labels><label><x>0</x><y>40</y><align>center</align><text_size>12</text_size><text><![CDATA[<b>" & sTitulo & "</b>]]></text></label></labels></settings>"") ")
            sb.AppendLine(", chart_data: encodeURIComponent(""" & Sdatos & """) };")
            sb.AppendLine("window.onload = function () {")
            sb.AppendLine(" if (swfobject.hasFlashPlayerVersion(""8"")) {swfobject.embedSWF(""amcharts/flash/ampie.swf?cache=0"", """ & DivId & """, """ & ancho & """, """ & alto & """, ""8.0.0"", ""amcharts/flash/expressInstall.swf"", flashVars, params);")
            sb.AppendLine(" }else {")
            sb.AppendLine(" var amFallback = new AmCharts.AmFallback();")
            sb.AppendLine(" amFallback.type = ""pie"";")
            sb.AppendLine("  amFallback.write(""" & DivId & """);")
            sb.AppendLine(" }")
            sb.AppendLine("}")
            If (cs.IsStartupScriptRegistered(DivId) = False) Then
                cs.RegisterStartupScript(cstype, DivId, sb.ToString(), True)
            End If
            Return ""
        Catch ex As Exception
            Return "<span>" & ex.Message & "</span>"
        End Try
    End Function

    Public Function genera_chart_column_Flash(ByRef DivId As String, ByRef Sdatos As String, ByRef sTitulo As String, ByRef pagina As Page, Optional ByVal ancho As Int32 = 600, Optional ByVal alto As Int32 = 400) As String
        Try
            Dim cstype As Type = pagina.GetType()
            Dim cs As ClientScriptManager = pagina.ClientScript
            Dim sb As StringBuilder = New StringBuilder()
            sb.AppendLine("var params ={bgcolor: ""#FFFFFF""}")
            sb.AppendLine("var flashVars = { path: ""amcharts/flash/"", chart_settings: encodeURIComponent(""<settings><background><alpha>100</alpha><border_alpha>0</border_alpha></background><grid><category><dashed>1</dashed></category><value><dashed>1</dashed></value></grid><axes><category><width>1</width><color>E7E7E7</color></category><value><width>1</width><color>E7E7E7</color></value></axes><values><value><min>0</min></value></values><balloon><alpha>62</alpha></balloon><column><type>stacked</type><width>26</width><alpha>85</alpha><border_alpha>9</border_alpha><balloon_text><![CDATA[En {series} {percents}% de las mejoras están {title}</b>]]></balloon_text><grow_time>3</grow_time></column><depth>15</depth><graphs><graph gid='0'><title>Stock</title><color>ADD981</color></graph><graph gid='1'><title>Column</title><color>7F8DA9</color></graph><graph gid='2'><title>Line</title><color>FEC514</color></graph></graphs><labels><label lid='0'><text><![CDATA[<b>" & sTitulo & "</b>]]></text><y>18</y><text_color>000000</text_color><text_size>13</text_size><align>center</align></label></labels></settings>"") ")
            sb.AppendLine(", chart_data: encodeURIComponent(""" & Sdatos & """) };")
            sb.AppendLine("window.onload = function () {")
            sb.AppendLine(" if (swfobject.hasFlashPlayerVersion(""8"")) {swfobject.embedSWF(""amcharts/flash/amcolumn.swf?cache=0"", """ & DivId & """, """ & ancho & """, """ & alto & """, ""8.0.0"", ""amcharts/flash/expressInstall.swf"", flashVars, params);")
            sb.AppendLine(" }else {")
            sb.AppendLine("  var amFallback = new AmCharts.AmFallback();")
            sb.AppendLine("  amFallback.pathToImages = ""amcharts/javascript/images/"";")
            sb.AppendLine("  amFallback.type = ""column"";")
            sb.AppendLine("  amFallback.write(""" & DivId & """);")
            sb.AppendLine(" }")
            sb.AppendLine("}")
            If (cs.IsStartupScriptRegistered(DivId) = False) Then
                cs.RegisterStartupScript(cstype, DivId, sb.ToString(), True)
            End If
            Return ""
        Catch ex As Exception
            Return "<span>" & ex.Message & "</span>"
        End Try
    End Function

    Public Function genera_chart_line_Flash(ByRef DivId As String, ByRef Sdatos As String, ByRef sTitulo As String, ByRef Graphs As String, ByRef pagina As Page, Optional ByVal ancho As Int32 = 600, Optional ByVal alto As Int32 = 400) As String
        Try
            Dim cstype As Type = pagina.GetType()
            Dim cs As ClientScriptManager = pagina.ClientScript
            Dim sb As StringBuilder = New StringBuilder()
            sb.AppendLine("var params ={bgcolor: ""#FFFFFF""}")
            sb.AppendLine("var flashVars = { path: ""amcharts/flash/"", chart_settings: encodeURIComponent(""<settings><text_color>oooooo</text_color><digits_after_decimal>2</digits_after_decimal><background><file></file></background><plot_area><margins><left>0</left><right>0</right><top>15</top></margins></plot_area><grid><x><alpha>0</alpha><approx_count>10</approx_count></x><y_left><color>FFFFF1</color><alpha>10</alpha></y_left></grid><axes><x><width>1</width><color>FFFFFF</color><alpha>0</alpha></x><y_left><width>1</width><alpha>0</alpha></y_left></axes><values><x><skip_first>1</skip_first><skip_last>1</skip_last></x><y_left><inside>1</inside><skip_last>1</skip_last><unit></unit><unit_position>left</unit_position></y_left></values><scroller><height>15</height><color>000000</color><alpha>30</alpha><bg_color>FFFFFF</bg_color><bg_alpha>20</bg_alpha></scroller><indicator><selection_color>000000</selection_color></indicator><legend><alpha>20</alpha><margins>15</margins><align>center</align><values><enabled>1</enabled><text>{value}</text></values></legend><zoom_out_button><alpha>100</alpha><text_color>FFFFFF</text_color><text_color_hover>000000</text_color_hover></zoom_out_button><graphs>" & Graphs & "</graphs><export_as_image><file>amcharts/flash/export.aspx</file><color>#CC0000</color><alpha>50</alpha></export_as_image><labels><label lid='0'><text><![CDATA[<b>" & sTitulo & "</b>]]></text><y>5</y><text_size>15</text_size><align>center</align></label></labels></settings>"") ")
            sb.AppendLine(", chart_data: encodeURIComponent(""" & Sdatos & """) };")
            sb.AppendLine("window.onload = function () {")
            sb.AppendLine(" if (swfobject.hasFlashPlayerVersion(""8"")) {swfobject.embedSWF(""amcharts/flash/amline.swf?cache=0"", """ & DivId & """, """ & ancho & """, """ & alto & """, ""8.0.0"", ""amcharts/flash/expressInstall.swf"", flashVars, params);")
            sb.AppendLine(" }else {")
            sb.AppendLine("  var amFallback = new AmCharts.AmFallback();")
            sb.AppendLine("  amFallback.pathToImages = ""amcharts/javascript/images/"";")
            sb.AppendLine("  amFallback.type = ""line"";")
            sb.AppendLine("  amFallback.write(""" & DivId & """);")
            sb.AppendLine(" }")
            sb.AppendLine("}")
            If (cs.IsStartupScriptRegistered(DivId) = False) Then
                cs.RegisterStartupScript(cstype, DivId, sb.ToString(), True)
            End If
            Return ""
        Catch ex As Exception
            Return "<span>" & ex.Message & "</span>"
        End Try
    End Function

    'JAVASCRIPT
    Public Function genera_chart_Pie_Javascript(ByRef DivId As String, ByRef Pagina As Page) As String
        Try
            Dim Qry As String = ""
            Dim cstype As Type = Pagina.GetType()
            Dim cs As ClientScriptManager = Pagina.ClientScript
            Dim sb As StringBuilder = New StringBuilder()
            sb.AppendLine("var chartData = [{ country: ""Implementada"", visits: 68 },{ country: ""En proceso de implementación"", visits: 16 },{ country: ""Sin implementar"", visits: 16}];")
            sb.AppendLine("var chart;")
            sb.AppendLine("window.onload = function () {")
            sb.AppendLine(" chart = new AmCharts.AmPieChart();")
            sb.AppendLine(" chart.dataProvider = chartData;")
            sb.AppendLine(" chart.titleField = ""country"";")
            sb.AppendLine(" chart.valueField = ""visits"";")
            sb.AppendLine(" chart.depth3D = 5;")
            sb.AppendLine(" chart.angle = 5;")
            sb.AppendLine(" chart.innerRadius = ""30%"";")
            sb.AppendLine(" chart.sequencedanimation = true;")
            sb.AppendLine(" chart.startDuration = 2;")
            sb.AppendLine(" chart.labelRadius = 30;")
            sb.AppendLine(" chart.colors = [""#B0DE09"", ""#0D52D1"", ""#FF0F00""];")
            sb.AppendLine(" chart.write(""" & DivId & """);")
            sb.AppendLine("}")
            If (cs.IsStartupScriptRegistered(DivId) = False) Then
                cs.RegisterStartupScript(cstype, DivId, sb.ToString(), True)
            End If
            Return ""
        Catch ex As Exception
            Return "<span>" & ex.Message & "</span>"
        End Try
    End Function
End Class

Public Class Md5_Class

    Public Function GetMd5Hash(ByVal input As String) As String
        Dim md5Hasher As MD5 = MD5.Create()
        Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))
        Dim sBuilder As New StringBuilder()
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i
        Return sBuilder.ToString()
    End Function

    Public Function VerifyMd5Hash(ByVal input As String, ByVal hash As String) As Boolean
        Dim hashOfInput As String = getMd5Hash(input)
        Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
        If 0 = comparer.Compare(hashOfInput, hash) Then
            Return True
        Else
            Return False
        End If
    End Function

End Class

Public Class Msgbox_Web
    Public Shared Sub CreateMessageAlertInUpdatePanel(ByVal up As UpdatePanel, ByVal strMessage As String)
        Dim guidKey As Guid = Guid.NewGuid()
        ScriptManager.RegisterStartupScript(up, up.GetType(), guidKey.ToString(), strMessage, True)
    End Sub
    Public Shared Sub CreateMessageAlert(ByVal strMessage As String)
        Dim guidKey As Guid = Guid.NewGuid()
        Dim pg As Page = HttpContext.Current.Handler
        Dim strScript As String = "alert('" & strMessage & "');"
        pg.ClientScript.RegisterStartupScript(pg.GetType(), guidKey.ToString(), strScript, True)
    End Sub
End Class

Public Class Permisos
    Public Shared Function Validar(ByVal Rol As Int16, ByVal IdPag As Int16) As Boolean
        Try
            Select Case Rol
                Case 1
                    Return True
                Case 2 And IdPag = 2
                    Return True
                Case 3 And IdPag = 3
                    Return True
                Case 4 And IdPag = 4
                    Return True
                Case 5 And IdPag = 5
                    Return True
                Case 6 And IdPag = 6
                    Return True
                Case 7 And IdPag = 7
                    Return True
                Case 8 And IdPag = 8
                    Return True
                Case Else
                    Return False
            End Select
            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function
End Class
Public Class geriatriaClases
    Public Shared Function fnbusquedaRapida(ByVal txtBusquedaRapida As String) As String
        Dim where As String
        where = " 1 = 1"
        where = where + " and (tipoDocumento like '%" + txtBusquedaRapida.Trim + "%'"
        where = where + " or documento like '%" + txtBusquedaRapida.Trim + "%'"
        where = where + " or primerNombre like '%" + txtBusquedaRapida.Trim + "%'"
        where = where + " or segundoNombre like '%" + txtBusquedaRapida.Trim + "%'"
        where = where + " or primerApellido like '%" + txtBusquedaRapida.Trim + "%'"
        where = where + " or segundoApellido like '%" + txtBusquedaRapida.Trim + "%')"
        Return where
    End Function
End Class
